import time, sys, pickle
from lib.uplink import Uplink
import lib.main, lib.checkout

def ignite(id, key, url, name):
    link = Uplink(url)
    upload = None
    checkout = lib.checkout.CheckOut(url)
    while True:
        print '##############################'
        status, response = 0, ''
        try:
            status, response = link.post('/rest/unit',{'nid':id,'key':key,'upload':upload})
            upload = None
        except Exception as e:
            print str(status) + ' connection error'
            print e.message
            link.reconnect()
        if status==200:
            print '#working...'
            unit = pickle.loads(response)
            #checking out
            completed = checkout.run('mapreduce/' + unit.link + '/')
            if not completed:
                self.log.error('can\'t checkout mapreduce')
                return
            #import ticket's mapreduce module
            processor = None
            module_name = 'trunk.mapreduce.' + unit.link
            print 'module_name',module_name
            #try:
            __import__(module_name)
            processor = sys.modules[module_name]
            #except:
                #print 'import failure'
            #run module
            print 'fetched unit id:',unit.id
            runit = processor.compute(unit)
            print 'finished computing'
            #upload result
            upload = pickle.dumps(runit)
        else:
            #log error
            print '~logging error'
            f = open('logs/error.html','w')
            f.write(response)
            f.close()
            #sleepy phase
            stime = 0
            print '~sleeping ['+str(stime)+']...'
            time.sleep(stime)


#####################################################################################
#Secondary functions
#####################################################################################
def eject(message):
    print message
    exit(-1)